<?php
declare (strict_types = 1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Config;
use think\facade\Cache;
use app\model\DingGroup as DingGroupModel;
use app\model\DingUser as DingUserModel;

class Dimission extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('dimission')
            ->setDescription('the dimission command');        
    }

    private function getAccessToken()
    {

        $redis = Cache::store('redis');
        $access_token = $redis->get('access_token');
        if(empty($access_token)){
            $url = sprintf("https://oapi.dingtalk.com/gettoken?appkey=%s&appsecret=%s",Config::get('dingding.appKey'),Config::get('dingding.appSecret'));
            $res = json_decode(curl_get($url),true);
            $access_token = $res['access_token'];
            $redis->set('access_token',$access_token,7000);
        }
        return $access_token;
    }


    public function getDimissionUsers($access_token){

        $isNext = true;
        $dingUserModel = new DingUserModel;
        $page = 1;
        $size = 50;

        while($isNext){

            $res = DingUserModel::where([])->order('id', 'asc')->paginate([
                'page' => $page,
                'list_rows' => $size
            ],false);

            $userid_list = [];

            foreach ($res as $key => $item) {
                $userid_list[] = $item['id'];
            }

            $page++;

            if(count($res) < 50){
                $isNext = false;
            }

            $url = sprintf("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/listdimission?access_token=%s",$access_token);

            $res = curl_post($url,[
                'userid_list' => implode(',', $userid_list),
            ]);

            $result = json_decode($res,true)['result'];

            foreach ($result as $key => $value) {

                if($value['status'] == 2){
                    $status = 1;
                }elseif($value['status'] == 1){
                    $status = 2;
                }else{
                    $status = 0;
                }

                if($status > 0){
                    $dingUserModel->update(['is_quit' =>$status],['id' => $value['userid']]);
                }

            
            }

        }


    }



    protected function execute(Input $input, Output $output)
    {

        $access_token = $this->getAccessToken();
        $this->getDimissionUsers($access_token);

    	// 指令输出
    	$output->writeln('dimission');
    }
}